import { Toast } from "vant";
import cTitle from "components/title";
import indexGoods from "../sachertorteComm/indexGoodsItem";
import yzService from "components/ui_components/yz_service";
import yzGoodsposter from "components/ui_components/yz_goodsPoster";
import yzSpecs from "components/ui_components/yz_specs";
export default {
  components: {
    cTitle,
    indexGoods,
    yzService,
    yzGoodsposter,
    yzSpecs
  },
  data() {
    return {
      swiperOption: {
        direction: "horizontal",
        autoHeight: true,
        autoplay: false,
        loop: true,
        initialSlide: 0,
        pagination: {
          el: ".swiper-pagination"
        }
      },
      city: "", //城市名称
      total: 0,
      clicktype: "", //弹窗打开还是关闭
      isPresell: 0, //是否是预售商品
      optionsId: "",
      optionsTitle: "",
      optionsObj: {}, //选中的规格包括活动时间
      timeData: {},
      beginStatus: 0, //判断商品状态
      goodsId: "",
      banner: [],
      shopList: [],
      iPnoneBottomBol: false,
      timeEndFlag: true,
      popupSpecs: false, //是否开启规格弹窗
      distance:'',
      cakeGoods: {},
      supplyCakeGoods: {},
      getGoods: {},
      groupCode: {}, //群活码
      is_favorite: {
        status: 0,
        message: "商品未收藏"
      },
      description: "", //自提门店说明
      brand: {
        id: 179,
        name: "测试品牌",
        logo: "1"
      },
      pluginSetting: {},
      cakeGoodsOption: [],
      shipAreaType: "",
      // 海报按钮
      posterShow: false,
      posterImg: null,
      isFrontCanvas: false, //是否前端控制生成海报，false为后端生成
      btnData2: {
        over_top: 450,
        icon_url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/bc_eweima.png"
      },
      btnData: {
        over_top: 500,
        icon_url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/icon-fontclass-zhiding.png"
      },
      //客服插件
      serviceShow: false,
      serviceQRcode: "",
      serviceMobile: "",
      cservice: "",
      canSame:0,
      canShip:0,
      canTake:0
    };
  },
  activated() {
    // this.optionsId = ""; //避免返回可以选择之前的规格购买
    if (this.$route.query.id) {
      this.goodsId = Number(this.$route.query.id);
    }
    if(this.$route.query.city) {
      this.city = this.$route.query.city;
      this.getRule();
      this.getDelivery();
    }
    this.fun
      .getLocation()
      .then(res => {
        this.locationStatus = true;
        if (this.city === "") {
          this.city = res.city;
          this.getRule();
          this.getDelivery();
        }
        
      })
      .catch(err => {
        console.log(err);
        this.locationStatus = false;
      });
    this.goodsdetails();
    this.serviceDetail();
  },
  methods: {
    backOn() {
      if (window.history.length <= 1) {
        this.$router.push(this.fun.getUrl("home", {}));
      } else {
        this.$router.back();
      }
    },
    toGroupCode() {
      //群活码跳转功能
      if (this.groupCode.jump_mode === "home") {
        this.$router.push(this.fun.getUrl("groupCode"));
      } else if (this.groupCode.code_url) {
        window.location.href = this.groupCode.code_url;
      }
    },
    goodsdetails() {
      let query = {
        id: this.goodsId,
        basic_info: 1
      };
      $http.get("goods.goods.get-goods-page", query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let getGoods = res.get_goods;
            let plugin = res?.plugin?.yz_supply_cake;
            let plugin_setting = response.basic_info?.plugin_setting;
            let groupCode = res?.plugin?.group_code; //群活码
            let yz_supply_cake_goods = plugin?.data?.yz_supply_cake_goods; //蛋糕叔叔格外的数据
            let goodsOption = yz_supply_cake_goods.has_many_yz_supply_cake_goods_option[0]; //结束时间处理
            let endTime = goodsOption.promotion_end_at || "";
            this.endTimeSpecs(goodsOption);
            this.getGoods = getGoods;
            this.pluginSetting = plugin_setting;
            this.cakeGoods = plugin?.data;
            this.supplyCakeGoods = yz_supply_cake_goods;
            this.groupCode = groupCode;
            this.promotionEndTime = this.endTimeFun(endTime?.replace(/-/g,'/'));
            this.cakeGoodsOption = yz_supply_cake_goods.has_many_yz_supply_cake_goods_option;
            this.beginStatus = this.endTimeSpecs(goodsOption);
            this.optionsObj = getGoods.has_many_options[0];
            if (plugin_setting?.yz_supply_cake?.is_ios_sell === 1 || plugin_setting?.yz_supply_cake?.is_ios_sell === "1") {
              // 卡券商品 并开启 IOS禁用
              if (this.fun.isIosOrAndroid() === "ios") {
                this.beginStatus = -1;
              }
            }
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    endTimeSpecs(ootionItem) {
      let endTime = ootionItem?.promotion_end_at; //结束时间处理
      let beginStatus = "";
      if (endTime) {
        //默认可能会没有时间常数
        let date = new Date(endTime.replace(/-/g,'/'));
        let current = new Date().getTime();
        if (date > current) {
          beginStatus = 2;
        }
      }
      return beginStatus;
    },
    endTimeFun(endTime) {
      let date = new Date(endTime);
      let timeDate = date.getTime();
      let current = new Date().getTime();
      return timeDate - current;
    },
    getRule() {
      let query = {
        city: this.city,
        goods_id: this.goodsId
      };
      $http.get("plugin.yz-supply-cake.frontend.index.index.getRule", query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            console.log(res.code);
            if (res.code !== 200) {
              Toast(res.data.msg);
              this.description = res.data.msg;
              return;
            }
            let data = res.data;
            this.description = data?.description;
            this.shipAreaType = data?.ship_area_type;
            this.shopList = data?.shop || [];
            if (this.shipAreaType === "2" || this.shipAreaType === 2) {
              //门店半径区域)
              let shipRule = JSON.parse(data?.ship_rule) || {};
              let nonDefault = shipRule.non_default || {};
              let distance = "";
              for (let key in nonDefault) {
                distance = nonDefault[key].distance;
              }
              this.distance = distance * 1000;
            }
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    getDelivery() { //配送方式
      let query = {
        city: this.city,
        goods_id: this.goodsId
      };
      $http.get("plugin.yz-supply-cake.frontend.index.index.getDistributionRules", query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            if (res.code !== 200) {
              Toast(res.data.msg);
              return;
            }
            let data = res.data;
            this.canSame = Number(data.can_same);
            this.canShip = Number(data.can_ship);
            this.canTake = Number(data.can_take);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    deliveryClick() {
      //跳转配送范围
      this.$router.push(this.fun.getUrl("deliveryArea", {}, { goodsId: this.goodsId, city: this.city }));
    },
    onTimeChange(e) {
      this.timeData = e.detail;
    },
    gotoMember() {
      //跳转会员中心
      this.$router.replace(this.fun.getUrl("member", {}, {}));
    },
    close_yz_specs_popup(e) {
      console.log(e);
      this.popupSpecs = false;
    },
    selectSpecsOn(optionsId, goodsCount) {
      //获取规格弹窗的数据是否显示可购买
      let optionItem = this.cakeGoodsOption.find((item, index) => {
        return item.option_id === optionsId;
      });
      let optionsObj = this.getGoods?.has_many_options.find((item, index) => {
        //显示规格文字
        return item.id === optionsId;
      });
      let endTime = this.endTimeFun(optionItem?.promotion_end_at || "") || "";
      this.optionsObj = optionsObj;
      this.total = goodsCount;
      this.optionsId = optionsId;
      this.beginStatus = this.endTimeSpecs(optionItem);
      this.promotionEndTime = endTime;
      if (goodsCount === 0) {
        this.beginStatus = -1;
      }
      if (this.pluginSetting?.yz_supply_cake?.is_ios_sell === 1 || this.pluginSetting?.yz_supply_cake?.is_ios_sell === "1") {
        // 卡券商品 并开启 IOS禁用
        if (this.fun.isIosOrAndroid() === "ios") {
          this.beginStatus = -1;
        }
      }
    },
    onService() {
      this.serviceShow = true;
    },
    cakeGoodsBuy() {
      this.popupSpecs = true;
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", { goods_id: this.goodsId }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    submitAction(event) {
      if (this.getGoods.has_option == 1 && !this.optionsId) {
        Toast("规格id不可为空，请选择规格");
        return;
      }
      this.popupSpecs = false;
      this.$nextTick(() => {
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              goodsId: this.goodsId,
              optionsId: this.optionsId,
              total: this.total,
              city:this.city,
              tag: "cake"
            }
          )
        );
      });
    },
    brandNav(brandId) {
      this.$router.push(this.fun.getUrl("sachertorteBandShop", {brand_id:brandId}, {city:this.city }));
    },
    onIndex() {
      //跳转首页
      this.$router.push(this.fun.getUrl("sachertorteIndex", {}, {city:this.city}));
    },
    //海报生成
    postShow() {
      if (!this.fun.isTextEmpty(this.posterImg)) {
        this.posterShow = true;
      } else {
        let toastPoster = Toast({
          duration: -1, // 持续展示 toast
          message: "正在为您生成海报中"
        });
        let url = "";
        let Jons = {};
        // this.isFrontCanvas = false;
        // this.isFrontCanvas = true;
        // url = "plugin.yz-supply-cake.frontend.goods.goods-poster.new-goods-poster";
        url = 'goods.goods-poster.generateGoodsPoster';

        Jons.id = this.goodsId;
        $http
          .get(url, Jons, "")
          .then(response => {
            toastPoster.clear();
            if (response.result == 1) {
              // isFrontCanvas 是否需要前端生成海报
              // this.posterImg = this.isFrontCanvas ? response.data : `${response.data.image_url}?${Date.now()}`;
              this.posterImg = response.data.image_url;
              console.log(this.posterImg)
              console.log(this.isFrontCanvas);
              this.posterShow = true;
            } else {
              this.posterShow = false;
              this.$dialog.alert({ message: response.msg });
            }
          })
          .catch(error => {
            toastPoster.clear();
            console.log(error);
          });
      }
      // this.posterShow = true;
      this.showSahre = true;
    },
    posterClick() {
      this.postShow();
    },
    posterClose() {
      this.posterShow = false;
    }
  }
};
